#include "wnjni.h"

/* This JNI function returns a reference to a new CSenseIndex Java object,
 * which represents the sense index entry for the sense key given by the
 * jSenseKey parameter, or the null reference if no sense index entry exists
 * for that sense key.
 *
 * If jSenseKey is NULL, this function throws an IllegalArgumentException and
 * returns NULL. If wninit( ), strdup( ), or GetSenseIndex( ) fail, this
 * function throws a WordNetException and returns NULL. If AllocObject( )
 * fails, this function returns NULL and propogates whatever Exception
 * AllocObject raised.
 *
 * No bounds-checking is performed on the JNIEnv or jclass parameters, since
 * the JVM is assumed to perform correctly. Undetermined behavior will result
 * if either of these variables are NULL.
 *
 * Implementation note: This function is glue for the WordNet library
 * function SnsIndexPtr GetSenseIndex( char* ).
 */

jobject Java_edu_princeton_cogsci_wn_ascii_CSenseIndex_lookup
( JNIEnv* env, jclass sic, jstring jSenseKey )
{
  if ( !jSenseKey )
  {
    env->ThrowNew(
      env->FindClass( "java/lang/IllegalArgumentException" ),
      "String senseKey was null."
    );
    return NULL;
  }
  jclass wordNetExceptionClass = env->FindClass( WORD_NET_EXCEPTION_CLASS );
  if ( wninit( ) )
  {
    env->ThrowNew( wordNetExceptionClass, "wninit( ) returned non-zero!" );
    return NULL;
  }

  // sic -- sense index class
  // sis -- sense index struct
  // sio -- sense index object

  char* senseKey = strdup( env->GetStringUTFChars( jSenseKey, NULL ) );
  if ( !senseKey )
  {
    env->ThrowNew( wordNetExceptionClass, "strdup( ) failed!" );
    return NULL;
  }

  SnsIndexPtr sis = GetSenseIndex( senseKey );
  free( senseKey );
  if ( !sis )
  {
    env->ThrowNew( wordNetExceptionClass, "GetSenseIndex( ) failed!" );
    return NULL;
  }

  jobject sio = env->AllocObject( sic );
  if ( !sio )
    return NULL;

  env->SetObjectField(
    sio,
    env->GetFieldID( sic, "sensekey", "Ljava/lang/String;" ),
    env->NewStringUTF( sis->sensekey )
  );
  env->SetObjectField(
    sio,
    env->GetFieldID( sic, "word", "Ljava/lang/String;" ),
    env->NewStringUTF( sis->word )
  );

  env->SetIntField(
    sio, env->GetFieldID( sic, "loc", "I" ), ( int )sis->loc
  );
  env->SetIntField(
    sio, env->GetFieldID( sic, "wnsense", "I" ), sis->wnsense
  );
  env->SetIntField(
    sio, env->GetFieldID( sic, "tag_cnt", "I" ), sis->tag_cnt
  );

  FreeSenseIndex( sis );
  return sio;
}



